package src.controller;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class achieve {
    private JFrame frame;
    private List<Achievement> achievements;
    private JPanel achievementsPanel;
    private JLabel statsLabel;

    // 成就类
    class Achievement {
        int id;
        String name;
        String condition;
        boolean completed;
        Date completionDate;

        Achievement(int id, String name, String condition, boolean completed) {
            this.id = id;
            this.name = name;
            this.condition = condition;
            this.completed = completed;
            if (completed) {
                this.completionDate = new Date();
            }
        }
    }

    public achieve() {
        // 初始化成就数据 - 完全按照图片内容
        achievements = new ArrayList<>();
        achievements.add(new Achievement(1, "成就名字", "成就达成条件", false));
        achievements.add(new Achievement(2, "成就名字", "成就达成条件", false));
        achievements.add(new Achievement(3, "成就名字", "成就达成条件", true));

        createAndShowGUI();
    }

    private void createAndShowGUI() {
        // 设置界面外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 创建主窗口
        frame = new JFrame("成就系统");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(850, 650);
        frame.setLocationRelativeTo(null);

        // 创建主面板
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setBackground(Color.WHITE);

        // 添加顶部区域（用户头像和统计信息）
        mainPanel.add(createTopPanel(), BorderLayout.NORTH);

        // 添加成就展示区域
        mainPanel.add(createAchievementsPanel(), BorderLayout.CENTER);

        // 添加底部按钮区域
        mainPanel.add(createButtonPanel(), BorderLayout.SOUTH);

        frame.add(mainPanel);
        frame.setVisible(true);
    }

    // 创建顶部面板（用户头像和统计信息）
    private JPanel createTopPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(Color.WHITE);
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 用户信息（左侧）
        JPanel userPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        userPanel.setBackground(Color.WHITE);

        // 用户头像（黑色圆形）
        JLabel avatar = new JLabel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(Color.BLACK);
                g2d.fillOval(0, 0, 50, 50);
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(50, 50);
            }
        };

        userPanel.add(avatar);

        // 用户名
        JLabel userName = new JLabel("用户");
        userName.setFont(new Font("微软雅黑", Font.BOLD, 16));
        userName.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
        userPanel.add(userName);

        // 统计信息（右侧）
        int total = achievements.size();
        int completed = (int) achievements.stream().filter(a -> a.completed).count();
        double completionRate = total > 0 ? (double) completed / total * 100 : 0;

        statsLabel = new JLabel(String.format("总成就: %d | 已完成: %d | 完成率: %.1f%%",
                total, completed, completionRate));
        statsLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        statsLabel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)
        ));

        panel.add(userPanel, BorderLayout.WEST);
        panel.add(statsLabel, BorderLayout.EAST);

        return panel;
    }

    // 创建成就展示面板
    private JPanel createAchievementsPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(Color.WHITE);
        panel.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));

        achievementsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 30, 0));
        achievementsPanel.setBackground(Color.WHITE);

        // 添加成就卡片
        renderAchievements();

        JScrollPane scrollPane = new JScrollPane(achievementsPanel);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        scrollPane.getViewport().setBackground(Color.WHITE);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);

        panel.add(scrollPane, BorderLayout.CENTER);
        return panel;
    }

    // 渲染成就卡片
    private void renderAchievements() {
        achievementsPanel.removeAll();

        for (Achievement achievement : achievements) {
            JPanel achievementPanel = createAchievementPanel(achievement);
            achievementsPanel.add(achievementPanel);
        }

        achievementsPanel.revalidate();
        achievementsPanel.repaint();
    }

    // 创建单个成就面板（严格按照图片样式）
    private JPanel createAchievementPanel(Achievement achievement) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBackground(Color.WHITE);
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));
        panel.setPreferredSize(new Dimension(220, 300));

        // 奖杯图标
        JPanel trophyPanel = createTrophyPanel(achievement.completed);
        trophyPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(trophyPanel);
        panel.add(Box.createRigidArea(new Dimension(0, 15)));

        // 成就信息（严格按照图片格式）
        JLabel infoLabel = new JLabel("<html><center>" + achievement.name +
                "<br>" + achievement.condition + "</center></html>");
        infoLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        infoLabel.setHorizontalAlignment(SwingConstants.CENTER);
        infoLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        panel.add(infoLabel);
        panel.add(Box.createRigidArea(new Dimension(0, 15)));

        // 进度显示（严格按照图片格式）
        JLabel progressLabel = new JLabel(achievement.completed ? "100%" : "--%");
        progressLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        progressLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        progressLabel.setForeground(achievement.completed ? Color.BLACK : Color.GRAY);
        panel.add(progressLabel);
        panel.add(Box.createRigidArea(new Dimension(0, 10)));

        // 进度条
        JProgressBar progressBar = new JProgressBar(0, 100);
        progressBar.setValue(achievement.completed ? 100 : 0);
        progressBar.setPreferredSize(new Dimension(150, 8));
        progressBar.setMaximumSize(new Dimension(150, 8));
        progressBar.setStringPainted(false);
        progressBar.setForeground(new Color(0, 120, 215));
        progressBar.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(progressBar);

        // 完成日期（仅对已完成的成就显示，严格按照图片格式）
        if (achievement.completed && achievement.completionDate != null) {
            panel.add(Box.createRigidArea(new Dimension(0, 10)));
            String dateStr = new SimpleDateFormat("yy年MM月dd日").format(achievement.completionDate);
            JLabel dateLabel = new JLabel("完成日期:" + dateStr);
            dateLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
            dateLabel.setFont(new Font("微软雅黑", Font.PLAIN, 10));
            dateLabel.setForeground(Color.GRAY);
            panel.add(dateLabel);
        }

        // 操作按钮区域
        panel.add(Box.createRigidArea(new Dimension(0, 15)));
        JPanel buttonPanel = createAchievementButtonPanel(achievement);
        buttonPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(buttonPanel);

        return panel;
    }

    // 创建奖杯面板（严格按照图片样式）
    private JPanel createTrophyPanel(boolean isCompleted) {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                int centerX = getWidth() / 2;
                int cupRadius = 30;

                if (isCompleted) {
                    // 黄色填充奖杯（已完成）
                    g2d.setColor(Color.YELLOW);
                    g2d.fillOval(centerX - cupRadius, 10, cupRadius * 2, cupRadius * 2);
                    g2d.setColor(Color.BLACK);
                    g2d.drawOval(centerX - cupRadius, 10, cupRadius * 2, cupRadius * 2);

                    // 奖杯把手（黄色填充）
                    g2d.setColor(Color.YELLOW);
                    g2d.fillRect(centerX - 10, 10 + cupRadius * 2, 20, 15);
                    g2d.setColor(Color.BLACK);
                    g2d.drawRect(centerX - 10, 10 + cupRadius * 2, 20, 15);
                } else {
                    // 黑色轮廓奖杯（未完成）
                    g2d.setColor(Color.BLACK);
                    g2d.drawOval(centerX - cupRadius, 10, cupRadius * 2, cupRadius * 2);

                    // 奖杯把手（黑色轮廓）
                    g2d.drawRect(centerX - 10, 10 + cupRadius * 2, 20, 15);
                }
            }
        };

        panel.setPreferredSize(new Dimension(100, 100));
        panel.setOpaque(false);
        return panel;
    }

    // 创建成就操作按钮面板
    private JPanel createAchievementButtonPanel(Achievement achievement) {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 0));
        panel.setBackground(Color.WHITE);

        // 切换完成状态按钮
        JButton toggleButton = new JButton(achievement.completed ? "标记未完成" : "标记完成");
        toggleButton.setFont(new Font("微软雅黑", Font.PLAIN, 10));
        toggleButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                toggleAchievementCompletion(achievement.id);
            }
        });

        // 删除按钮
        JButton deleteButton = new JButton("删除");
        deleteButton.setFont(new Font("微软雅黑", Font.PLAIN, 10));
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteAchievement(achievement.id);
            }
        });

        panel.add(toggleButton);
        panel.add(deleteButton);

        return panel;
    }

    // 创建功能按钮面板
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
        panel.setBackground(Color.WHITE);
        panel.setBorder(BorderFactory.createEmptyBorder(10, 0, 20, 0));

        JButton addButton = new JButton("添加成就");
        addButton.setFont(new Font("微软雅黑", Font.BOLD, 12));
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addAchievement();
            }
        });

        JButton statsButton = new JButton("数据统计");
        statsButton.setFont(new Font("微软雅黑", Font.BOLD, 12));
        statsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showStatistics();
            }
        });

        panel.add(addButton);
        panel.add(statsButton);

        return panel;
    }

    // 添加成就功能
    private void addAchievement() {
        JTextField nameField = new JTextField("成就名字");
        JTextField conditionField = new JTextField("成就达成条件");

        Object[] message = {
                "成就名称:", nameField,
                "达成条件:", conditionField
        };

        int option = JOptionPane.showConfirmDialog(frame, message, "添加新成就",
                JOptionPane.OK_CANCEL_OPTION);

        if (option == JOptionPane.OK_OPTION) {
            String name = nameField.getText().trim();
            String condition = conditionField.getText().trim();

            if (!name.isEmpty() && !condition.isEmpty()) {
                int newId = achievements.size() > 0 ?
                        achievements.get(achievements.size() - 1).id + 1 : 1;
                Achievement newAchievement = new Achievement(newId, name, condition, false);
                achievements.add(newAchievement);
                refreshUI();
                JOptionPane.showMessageDialog(frame, "成就添加成功！");
            }
        }
    }

    // 删除成就功能
    private void deleteAchievement(int id) {
        int result = JOptionPane.showConfirmDialog(frame,
                "确定要删除这个成就吗？", "确认删除", JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION) {
            achievements.removeIf(a -> a.id == id);
            refreshUI();
            JOptionPane.showMessageDialog(frame, "成就已删除！");
        }
    }

    // 切换成就完成状态
    private void toggleAchievementCompletion(int id) {
        for (Achievement achievement : achievements) {
            if (achievement.id == id) {
                achievement.completed = !achievement.completed;
                if (achievement.completed) {
                    achievement.completionDate = new Date();
                } else {
                    achievement.completionDate = null;
                }
                break;
            }
        }
        refreshUI();
    }

    // 显示统计数据
    private void showStatistics() {
        int total = achievements.size();
        int completed = (int) achievements.stream().filter(a -> a.completed).count();
        double completionRate = total > 0 ? (double) completed / total * 100 : 0;

        String statsText = String.format(
                "总成就数: %d\n已完成: %d\n完成率: %.1f%%",
                total, completed, completionRate
        );

        JOptionPane.showMessageDialog(frame, statsText, "数据统计", JOptionPane.INFORMATION_MESSAGE);
    }

    // 刷新界面
    private void refreshUI() {
        // 更新统计信息
        int total = achievements.size();
        int completed = (int) achievements.stream().filter(a -> a.completed).count();
        double completionRate = total > 0 ? (double) completed / total * 100 : 0;

        statsLabel.setText(String.format("总成就: %d | 已完成: %d | 完成率: %.1f%%",
                total, completed, completionRate));

        // 重新渲染成就卡片
        renderAchievements();

        // 刷新界面
        frame.revalidate();
        frame.repaint();
    }

    // 主方法
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new achieve();
            }
        });
    }
}